<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>视频播放页 - 哔哩哔哩</title>
    <script src="http://47.106.66.89:8080/js/vue.min.js"></script>
    <script src="http://47.106.66.89:8080/js/axios.min.js"></script>
    <link  href="http://47.106.66.89:8080/js/ele-2.15.7/theme-chalk/index.css" rel="stylesheet">
    <script src="http://47.106.66.89:8080/js/ele-2.15.7/index.js"></script>
    <link href="css/video.css" rel="stylesheet">
    <link href="css/common.css" rel='stylesheet'>
    <script src="/b-user/js/login.js"></script>
    <script src="/b-chat/js/ws.js"></script>
    <script src="js/common.js"></script>
</head>
<body>
<div id="app">
<!--    <ws ref="w" :msgs.sync="msgs" :users.sync="users" prefix="ws://127.0.0.1:8004/"></ws>-->
    <common @logined="logined"></common>
    <div class="container">
        <!-- 左侧主要内容 -->
        <div class="main-content">

            <div class="video-info">
                <h1 class="video-title">《似锦》：建议文盲禁止当编剧！尬燃大女主令人智痴！</h1>
                <div class="video-meta">
                    <span>54.5万播放</span> ·
                    <span>2025-03-05 12:05:00</span>
                </div>
            </div>

            <div id="video-player">
                <video  ref="video" class="video" :src="userandvideo.path" controls loop autoplay></video>
            </div>

            <div class="danmu-control">
                <ul style="display: flex; justify-content:space-between; align-items: baseline; font-size: larger; width: 668px; list-style: none;">
                    <li><span>在线人数:</span></li>
                    <li><img src="image/弹幕.png" style="width: 25px; height: 25px;"></li>
                    <li><img src="image/弹幕设置.png" style="width: 25px; height: 25px;"></li>
                    <li style="position: relative; top: -10px"><input id="inputText" v-model="danmuText"><input id="danmuInput" @click="savedanmu()" value="发送弹幕" type="button" style="background-color: skyblue;"></li>
                </ul>
            </div>

            <div class="action-buttons">
                <div class="action-btn">
                    <span>1.3万</span>
                    <img src="image/点赞_黑色.png" style="width: 25px">
                </div>
                <div class="action-btn">
                    <span>1426</span>
                    <img src="image/投币@2x.png" style="width: 25px">
                </div>
                <div class="action-btn">
                    <span>727</span>
                    <img src="image/收 藏.png" style="width: 25px">
                </div>
                <div class="action-btn">
                    <span>727</span>
                    <img src="image/转发.png" style="width: 25px">
                </div>
            </div>
            <hr/>

            <div class="video-tags">
                <span class="video-tag">建议提高编剧准入门槛</span>
                <span class="video-tag">人人都能聊视频</span>
            </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar">
            <div class="author-info">
                <div class="author-header">
                    <img :src="userandvideo.headimg" class="author-avatar">
                    <div>
                        <h3>{{userandvideo.name}}</h3>
                        <p>粉丝：{{userandvideo.fens > 10000 ? userandvideo.fens / 10000 + '万' : userandvideo.fens}}</p>
                    </div>
                </div>
                <button class="send-btn">+ 关注</button>
            </div>

            <h3>相关推荐</h3>
            <div class="related-video">
                <img class="related-thumb" >
                <div>
                    <h3>宅斗？傻斗！文盲编剧再就业</h3>
                    <div class="re-video-message">
                        <p>老郭说电影</p>
                        <p>15.2万播放 · 1754弹幕</p>
                    </div>
                </div>
            </div>
            <!-- 更多推荐视频... -->
        </div>
    </div>
</div>

<script>
    var v = new Vue({
        el : "#app",
        data : {
            userandvideo:{},
            myinfo: null,
            endtime: 0,
            msgs:{},
            users:{},
            danmuText: "",
            danmus:[],
            showedDanmus: []  // 存储已显示的弹幕ID（避免重复显示
        },
        created() {
            axios.get("video/getVideoByVid"+location.search).then(res=> this.userandvideo = res.data);
            axios.get("danmu/getDanmuByVid"+location.search).then(res=> {
                this.danmus = res.data
                this.loadDanMus();
            });

        },
        methods : {
            logined(myinfo){
                this.myinfo = myinfo
                // 加载视频进度
                axios.get("videoplayhistroy/getvideodenTime", {
                    params:{
                        uid: this.myinfo.id,
                        vid: location.search.split("=")[1]
                    }
                }).then(res=>{
                    if(res.data){
                        this.endtime = res.data.endtime
                        this.$refs.video.currentTime = this.endtime; // 视频跳转
                    }
                })
            },

            saveVideoProgress() {
                const videoplayhistroy={
                    uid: this.myinfo.id,
                    vid: location.search.split("=")[1],
                    endtime: this.$refs.video.currentTime
                }
                if (this.$refs.video) {
                    axios.post("videoplayhistroy/saveVideoProgress", videoplayhistroy)
                }
            },





            ////////////////////////

            // 创建WebSocket连接（需要替换为实际后端地址）
            // const ws = new WebSocket('ws://your-websocket-server:port');



            // WebSocket连接成功
            // ws.onopen = () => {
            //     console.log('WebSocket连接已建立');
            // };

            // 接收弹幕消息
            // ws.onmessage = (event) => {
            //     const danmuData = JSON.parse(event.data);
            //     createDanmuElement(danmuData);
            // };

            // 创建弹幕元素
            createDanmuElement(text) {
                if(!text || text.trim() === ""){
                    this.$alert("请输入内容")
                    return 0;
                }
                // console.log(Object.keys(this.myinfo).length)
                if(!this.myinfo){
                    this.$alert("请先登录")
                    return 0;
                }
                // 弹幕容器引用
                const danmuBox = document.getElementById('video-player');
                const data = text;
                const danmu = document.createElement('div');
                danmu.className = 'danmu';
                danmu.textContent = data;
                danmu.style.color = "red";

                const DomRect = document.getElementById('video-player').getBoundingClientRect();



                danmu.style.top = `${Math.random() * (DomRect.height - 40)}px`; // 随机垂直位置

                danmuBox.appendChild(danmu);

                const dummy = danmu.offsetWidth

                const itemWidth = danmu.offsetWidth; // 获取弹幕元素的宽度
                const containerWidth = danmuBox.offsetWidth; // 获取显示区域的宽度

                // 设置弹幕的起始位置（显示区域右侧外部）
                danmu.style.left = `${DomRect.width - itemWidth}px`;

                // 定义动画关键帧
                const animationName = `moveBarrage${danmu.id}`;
                const css = `
                    @keyframes ${animationName} {
                    from {
                        transform: translateX(100%);
                    }
                    to {
                        transform: translateX(-${containerWidth}px);
                    }
                    }
                `;
                // 将CSS添加到文档中（仅当该动画尚未定义时）
                if (!document.getElementById(animationName)) {
                    const style = document.createElement('style');
                    style.id = animationName;
                    style.textContent = css;
                    document.head.appendChild(style);
                }

                // 应用动画到弹幕元素
                danmu.style.animation = `${animationName} 5s linear forwards`; // 动画持续时间为5秒，可以根据需要调整


                // 动画结束后移除元素
                danmu.addEventListener('animationend', () => {
                    danmu.remove();
                });


            },
            savedanmu(){
                var number = this.createDanmuElement(this.danmuText);
                if(number == 0){
                    return;
                }
                const danmuData = {
                    uid: this.myinfo.id,
                    vid: location.search.split("=")[1],
                    content: this.danmuText,
                    videotime: this.$refs.video.currentTime

                }
                // 将弹幕数据发送到服务端
                axios.post("danmu/savedanmu", danmuData)
            },

            // 发送弹幕
             sendDanmu() {
                const input = document.getElementById('danmuInput');
                const color = document.getElementById('colorPicker').value;

                if (input.value.trim()) {
                    const message = {
                        text: input.value,
                        color: color,
                        timestamp: Date.now()
                    };

                    // 通过WebSocket发送消息
                    ws.send(JSON.stringify(message));
                    input.value = '';
                }
            },
            loadDanMus(){
                // 在数据加载完成后，可以执行相关逻辑，例如监听 timeupdate 事件
                this.$refs.video.addEventListener('timeupdate', () => {
                    this.danmus.forEach(danmu => {
                        const videoTiem = this.$refs.video.currentTime
                        if (!this.showedDanmus.includes(danmu.id) && Math.abs(videoTiem - danmu.videotime) < 0.3) {
                            this.createDanmuElement(danmu.content);
                            this.showedDanmus.push(danmu.id)
                        }
                    });
                });
            }
        },
        mounted(){
                // // 回车发送支持
                // document.getElementById('danmuInput').addEventListener('keypress', (e) => {
                //     if (e.key === 'Enter') sendDanmu();
                // });
                // 添加 beforeunload 事件监听器, 当用户离开此页面时触发
                window.addEventListener('beforeunload', this.saveVideoProgress);
            },
            beforeDestroy() {
                // 移除事件监听器
                window.removeEventListener('beforeunload', this.saveVideoProgress);
                // 组件销毁前也保存一次进度
                this.saveVideoProgress();
            },
        })
</script>


<script>
    // 弹幕开关功能
    // const danmuSwitch = document.getElementById('danmuSwitch');
    // danmuSwitch.addEventListener('change', function() {
    //     console.log('弹幕状态：', this.checked);
    // });

    // // 互动按钮功能
    // document.querySelectorAll('.action-btn button').forEach(btn => {
    //     btn.addEventListener('click', function() {
    //         this.closest('.action-btn').classList.toggle('active');
    //     });
    // });

    // // 弹幕发送功能
    // document.querySelector('.send-btn').addEventListener('click', function() {
    //     const input = document.querySelector('.danmu-input');
    //     if (input.value.trim()) {
    //         console.log('发送弹幕：', input.value);
    //         input.value = '';
    //     }
    // });
</script>

<script>

</script>
</body>
</html>